package list.circle;

import list.AbstractList;

public class SingeCircleLinkedList<E> extends AbstractList<E> {
	
	private Node<E> first;
	
	
	@Override
	public void add(int index, E element) {
		checkIndexForAdd(index);
		if (index == 0) {
			Node<E> newFirst = new Node<>(element, first);
			Node<E> last = size == 0 ? newFirst : node(size - 1);
			first = newFirst;
			last.next = first;
		} else {
			Node<E> prev = node(index - 1);
			prev.next = new Node<>(element, prev.next);
		}
		size++;
	}

	@Override
	public E get(int index) {
		return node(index).element;
	}

	@Override
	public E set(int index, E element) {
		Node<E> node = node(index);
		E oldElement = node.element;
		node.element = element;
		return oldElement;
	}

	@Override
	public E remove(int index) {
		checkIndex(index);
		E oldElement = null;
		if (index == 0) {
			oldElement = first.element;
			if (size == 0) {
				first = null;
			} else {
				Node<E> last = node(size - 1);
				first = first.next;
				last.next = first;
			}
		} else {
			Node<E> prev = node(index - 1);
			oldElement = prev.next.element;
			prev.next = prev.next.next;
		}
		size--;
		return oldElement;
	}

	@Override
	public int indexOf(E element) {
		if (element == null) {
			Node<E> node = first;
			for (int i = 0; i < size; i++) {
				if (node.element == null) return i;
				node = node.next;
			}
		} else {
			Node<E> node = first;
			for (int i = 0; i < size; i++) {
				if (element.equals(node.element)) return i;
				node = node.next;
			}
		}
		return ELEMENT_NOT_FOUND;
	}

	@Override
	public void clear() {
		size = 0;
		first = null;
	}
	
	@Override
	public String toString() {
		if (size == 0) return "[]";
		StringBuilder sb = new StringBuilder(size << 2 + 50);
		sb.append("[");
		Node<E> node = first;
		for (int i = 0; i < size; i++) {
			if (i != 0) {
				sb.append(", ");
			}
			sb.append(node.element).append("_").append(node.next.element);
			node = node.next;
		}
		sb.append("]");
		return sb.toString();
	}
	
	private Node<E> node(int index) {
		checkIndex(index);
		Node<E> node = first;
		for (int i = 0; i < index; i++) {
			node = node.next;
		}
		return node;
	}
	
	private static class Node<E> {
		E element;
		Node<E> next;
		
		public Node(E element, Node<E> next) {
			this.element = element;
			this.next = next;
		}
	}
	
	
}
